// 定义一个用于分割文本的类
class GovDocTextSplitter {
  // 定义最大和最小段落大小
  static maxSize = 400;
  static minSize = 100;

  // 静态方法用于分割文本
  static splitText(text) {
    const splitter = new GovDocTextSplitterHelper(this.maxSize);
    // 分割文本并过滤掉长度小于10的段落
    return splitter.splitText(text).filter((item) => item.length > 10);
  }
}
// 辅助类用于处理具体的文本分割逻辑
class GovDocTextSplitterHelper {
  constructor(maxSize) {
    this.maxSize = maxSize;
    // 定义分隔符的正则表达式模式
    this.separatorPatterns = [
      /\n[一二三四五六七八九十百千万亿]+\s?[、]+/g,
      /[（]+\s?[第一二三四五六七八九十百千万亿]+\s?[）]+\s?/g,
      /\d+[．]\s?/g,
      /[（]+\s?\d+\s?[）]+/g,
      /(\n\n|\n)/g,
    ];
  }
  // 检查文本是否为空
  isTextEmpty(text) {
    return text.trim().length === 0;
  }
  // 获取文本长度
  getTextLength(text) {
    return text.length;
  }
  // 分割文本的方法
  splitText(text) {
    const finalChunks = [];
    // 如果文本长度超过最大值，递归分割
    if (this.getTextLength(text) > this.maxSize) {
      finalChunks.push(...this.recursiveSplitText(0, text));
    } else {
      // 否则直接添加到结果中
      if (!this.isTextEmpty(text)) {
        finalChunks.push(text);
      }
    }
    const finalWords = this.mergeShortChunks(finalChunks);
    // 合并短段落
    return finalWords;
  }
  // 递归分割文本的方法
  recursiveSplitText(layer, text) {
    const finalChunks = [];
    const patternLayerMax = this.separatorPatterns.length;

    // 如果超过最大层数，使用句号等分隔符分割
    if (layer >= patternLayerMax) {
      if (this.getTextLength(text) <= 1000) {
        const lineCount = Math.ceil(this.getTextLength(text) / 200);
        const splitsArr = text.split(/(?<=[。；？])/);

        if (splitsArr.length < lineCount) {
          splitsArr.forEach((split) => finalChunks.push(split.trim()));
        } else {
          const mergedChunks = [];
          let currentIndex = 0;

          while (currentIndex < splitsArr.length) {
            let chunk = "";
            let countInChunk = 0;

            while (
              currentIndex < splitsArr.length &&
              countInChunk < Math.ceil(splitsArr.length / lineCount)
            ) {
              chunk += splitsArr[currentIndex].trim();
              currentIndex++;
              countInChunk++;
            }

            mergedChunks.push(chunk);
          }

          mergedChunks.forEach((split) => finalChunks.push(split.trim()));
        }
      }
    } else {
      // 使用当前层的分隔符分割文本
      if (this.getTextLength(text) < this.maxSize) {
        finalChunks.push(text.trim()); // TODO: 加了个trim
      } else {
        const separatorPattern = this.separatorPatterns[layer];
        let processed = 0;
        let match;

        while ((match = separatorPattern.exec(text)) !== null) {
          const posStart = match.index;
          const subText = text.slice(processed, posStart);

          if (this.getTextLength(subText) < this.maxSize) {
            if (!this.isTextEmpty(subText)) {
              finalChunks.push(subText.trim()); // TODO: 加了个trim
            }
          } else {
            finalChunks.push(...this.recursiveSplitText(layer + 1, subText));
          }
          processed = posStart + match[0].length;
        }

        // 处理最后一段文本
        const lastText = text.slice(processed);
        if (this.getTextLength(lastText) < this.maxSize) {
          if (!this.isTextEmpty(lastText)) {
            finalChunks.push(lastText.trim()); // TODO: 加了个trim 去除段落之间的空格
          }
        } else {
          finalChunks.push(...this.recursiveSplitText(layer + 1, lastText));
        }
      }
    }

    return finalChunks;
  }
  // 合并短段落的方法
  mergeShortChunks(chunks) {
    const mergedChunks = [];
    let i = 0;

    while (i < chunks.length) {
      let currentChunk = chunks[i];

      // 合并小于最小长度的段落
      while (
        currentChunk.length < GovDocTextSplitter.minSize &&
        i + 1 < chunks.length
      ) {
        const nextChunk = chunks[i + 1];
        const merged = currentChunk + nextChunk;
        // 如果合并后的段落超过最大长度则停止合并
        if (merged.length > GovDocTextSplitter.maxSize) {
          break;
        } else {
          currentChunk = merged;
          i++;
        }
      }
      mergedChunks.push(currentChunk);
      i++;
    }

    return mergedChunks;
  }
}

// 导出 GovDocTextSplitter 类
export { GovDocTextSplitter };
